<?php
/**
 * Created by PhpStorm.
 * Script Name: Templatemsg.php
 * Create: 11/1/22 11:00 PM
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace app\common\coroutine\handler;

use app\common\coroutine\Handler;
use EasyWeChat\Factory;
use GuzzleHttp\Client;
use ky\ErrorCode;
use Symfony\Component\Cache\Adapter\RedisAdapter;

class TestHandler  extends Handler
{
    private $module = 'test';
    private static $http = null;

    public static function getHttpClient(){
        if(self::$http == null){
            self::$http = new Client([
                'timeout'  => 0
            ]);
        }
        return self::$http;
    }

    function onTask($server, $task_id, $reactor_id, $data)
    {
        //sleep(1);
        echo '执行任务：' . $data['data'] . PHP_EOL;
        if(!empty($data['mp_info'])){
            $api = $this->getMpApp($data['mp_info'])->user;
            var_dump($api->get($data['data']));
            echo PHP_EOL;
        }
        //self::getHttpClient()->get('http://example.com/');
        $server->finish([
            'module' => $this->module,
            'data' => $data['data']
        ]);
    }

    function onFinish($server, $task_id, $data)
    {
        echo date("Y-m-d H:i:s") . "  完成任务:" . $data['data'] . PHP_EOL;
    }

    function onReceive($server, $fd, $from_id, $data)
    {
        $mp_info = $data['mp_info'];
        $list = $data['list'];
        foreach ($list as $key => $value) {
            // 投递异步任务
            $server->task([
                'module' => $data['module'],
                'data' => $value,
                'mp_info' => $mp_info,
            ]);
        }
    }

    /**
     * 获取公众号APP
     * @param $mp_info
     * @return \EasyWeChat\OfficialAccount\Application|\EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Application
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \Exception
     */
    private function getMpApp($mp_info){
        $config = [
            'app_id'   => '',
            'secret'   => '',
            'token'    => '',
            'response_type' => 'array',
            'log' => [
                'level' => 'error',
                'file'  => RUNTIME_PATH . 'log/mp-'.$mp_info['id'].'.log',
            ]
        ];
        if($mp_info['appsecret']){
            $config['aes_key'] = $mp_info['encodingaeskey'];
            $config['app_id'] = $mp_info['appid'];
            $config['secret'] = $mp_info['appsecret'];
            $config['token'] = $mp_info['refresh_token'];
            return Factory::officialAccount($config);
        }else{
            return $this->getOpenPlatform()->officialAccount($mp_info['appid'], $mp_info['refresh_token']);
        }
    }

    private function getOpenPlatform(){
        $platform = config('system.weixin.platform');
        if(empty($platform)){
            throw  new \Exception("开放平台参数未配置", ErrorCode::WxCompException);
        }
        $config = [
            'app_id' => $platform['appid'],
            'secret'   => $platform['appsecret'],
            'token'    => $platform['token'],
            'aes_key'  => $platform['aes_key']
        ];
        $app = Factory::openPlatform($config);

        //composer require predis/predis
        $client = new \Predis\Client('tcp://'.config('cache.redis.host').':' . config('cache.redis.port'));
        $app->rebind('cache', new RedisAdapter($client));
        return  $app;
    }
}